package com.xnfh.planting.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.PolygonOptions
import com.flyco.tablayout.SlidingTabLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.xnfh.common.bean.Record
import com.xnfh.common.pop.OpenAddressPop
import com.xnfh.common.utils.LocationEnclosureUtil
import com.xnfh.common.utils.ViewFindUtils
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.utils.JsonUtlis
import com.xnfh.planting.R
import com.xnfh.planting.databinding.ActivityPlantFieldDetailBinding
import com.xnfh.common.adapter.MyPageAdapter
import com.xnfh.planting.ui.fragment.FindFieldRecordsFragment
import com.xnfh.planting.ui.fragment.PlantOptionFragment
import com.xnfh.planting.utils.PlantFieldDetailMapUtil

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/12/12 09:48
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/12/12 09:48
 * @UpdateRemark: 更新说明
 */
class PlantFieldDetailActivity : BaseActivity<ActivityPlantFieldDetailBinding>() {
    override fun getLayoutID(): Int = R.layout.activity_plant_field_detail

    companion object {
        fun start(context: Context, bundle: Bundle? = null) {
            val intent = Intent(context, PlantFieldDetailActivity::class.java)
            if (bundle != null) {
                intent.putExtra("bundle", bundle)
            }
            context.startActivity(intent)
        }
    }

    private val mTitles = ArrayList<String>()
    private val mFragment = ArrayList<Fragment>()

    private var aMap: AMap? = null
    private var currLocationMarker: Marker? = null
    private var curLatLng: LatLng? = null
    private var fieldBounds: LatLngBounds? = null

    //传入的地块信息
    private var fieldDetailBean: Record? = null

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true).statusBarColor(R.color.white) //状态栏字体是深色，不写默认为亮色
        }
    }

    override fun init(savedInstanceState: Bundle?) {
        val bundleExtra = intent.getBundleExtra("bundle")
        //页面的两个fragment也有用到这个bean，如果这里删除，也要看一下fragment
        fieldDetailBean = bundleExtra?.getSerializable("data") as Record
        //初始化地图基本信息
        initMapView(savedInstanceState)
        //地块信息，展示在地图上
        initFieldMessage()
        val tabLayout = ViewFindUtils.find<SlidingTabLayout>(
            window.decorView,
            R.id.plant_fleld_detail_tablayout
        )
        mTitles.add(getString(R.string.plant_option))//种植方案
        mTitles.add(getString(R.string.find_field_records))//巡田记录
        mFragment.add(PlantOptionFragment.getInstance(bundleExtra))
        mFragment.add(FindFieldRecordsFragment.getInstance(bundleExtra))
        val myPageAdapter = MyPageAdapter(supportFragmentManager, mFragment, mTitles)
        mBind.plantFleldDetailViewpage.adapter = myPageAdapter
        tabLayout.setViewPager(mBind.plantFleldDetailViewpage)
    }

    /**
     * 设置地块信息
     */
    private fun initFieldMessage() {
        if (fieldDetailBean == null) return
        //地块名称
        mBind.plantFieldHeader.headerTitleTxt.text = fieldDetailBean?.fieldName
        try {
            val gpsList = JsonUtlis.toTwoArrayList(fieldDetailBean?.borderCoordinate)
            val builder = LatLngBounds.builder()
            val latLngList: MutableList<LatLng> = ArrayList()
            for (j in gpsList.indices) {
                val lon = gpsList[j][0]
                val lat1 = gpsList[j][1]
                val latLng = LatLng(lat1, lon)
                latLngList.add(latLng)
                builder.include(latLng)
            }
            latLngList.add(LatLng(gpsList[0][1], gpsList[0][0]))
            val polygonOpt =
                PolygonOptions().fillColor(0x4D3E9BFD).strokeColor(-0xbf6302)
                    .strokeWidth(10f)
            polygonOpt.zIndex(2f)
            val fieldPolygon = aMap!!.addPolygon(polygonOpt)
            fieldPolygon?.points = latLngList
            val centerCoordinate = fieldDetailBean?.centerCoordinate?.replace("[", "")?.replace("]", "")
            val lng = centerCoordinate!!.split(",")[0].toDouble()
            val lat = centerCoordinate.split(",")[1].toDouble()
            val latLng = LatLng(lat, lng)
            aMap!!.addMarker(
                MarkerOptions().position(latLng)
                    .icon(BitmapDescriptorFactory.fromResource(com.xnfh.common.R.mipmap.field_navigation_img))
            )
            fieldBounds = builder.build()
            //默认展示地块的tab信息
            showAndHiddenDetailSelectTab(true)
        } catch (e: Exception) {
            e.printStackTrace()
            LogUtil.e("加载地块详情地图抛出异常：${e}")
        }
    }

    override fun observe() {

    }

    /**
     * 初始化地图相关
     */
    private fun initMapView(savedInstanceState: Bundle?) {
        mBind.plantFieldDetailMap.onCreate(savedInstanceState)
        aMap = PlantFieldDetailMapUtil.init(
            mBind.plantFieldDetailMap,
            { location ->
                if (location != null) {
                    val latitude: Double = location.latitude
                    val longitude: Double = location.longitude
                    curLatLng = LatLng(
                        LocationEnclosureUtil.GCJ2WGSLat(latitude, longitude),
                        LocationEnclosureUtil.GCJ2WGSLon(latitude, longitude)
                    )

                    if (currLocationMarker == null) {
                        currLocationMarker = aMap?.addMarker(
                            MarkerOptions().position(curLatLng)
                                .icon(BitmapDescriptorFactory.fromResource(com.xnfh.common.R.mipmap.arrows_img))
                                .anchor(0.5f, 0.5f)
                        )
                    } else {
                        currLocationMarker?.position = curLatLng
                    }
                }
            }, {
                //map的点击事件
                showAndHiddenDetailSelectTab(mBind.fieldDetailMessageCon.visibility == View.GONE)
            }) {
            val openAddressPop = OpenAddressPop(this@PlantFieldDetailActivity)
            XPopup.Builder(this@PlantFieldDetailActivity)
                .setPopupCallback(object : SimpleCallback() {
                    override fun onCreated(popupView: BasePopupView?) {
                        super.onCreated(popupView)
                        openAddressPop.setLonandlat(fieldDetailBean!!.center02)
                    }
                }).asCustom(openAddressPop).show()
            false
        }

    }

    /**
     * @param isShow 是否展示
     */
    private fun showAndHiddenDetailSelectTab(isShow: Boolean) {
        //点击map，判断底部相信信息是否展示
        if (!isShow) {
            mBind.fieldDetailMessageCon.visibility = View.GONE
            //调整地块在map的展示
            aMap?.animateCamera(
                CameraUpdateFactory.newLatLngBoundsRect(
                    fieldBounds,
                    200,
                    200,
                    400,
                    400
                )
            )
        } else {
            mBind.fieldDetailMessageCon.visibility = View.VISIBLE
            aMap?.animateCamera(
                CameraUpdateFactory.newLatLngBoundsRect(
                    fieldBounds,
                    200,
                    200,
                    50,
                    1100
                )
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mFragment.forEach {
            it.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBind.plantFieldDetailMap.onDestroy()
        PlantFieldDetailMapUtil.destory()
    }
}